package com.lagou.config;

import com.lagou.io.Resources;
import com.lagou.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * 采用 dom4j 解析配置信息
 *
 * @author srh
 * @date 2020/02/22
 **/
public class XmlConfigBuilder {

    private Configuration configuration;

    public XmlConfigBuilder() {
        this.configuration = new Configuration();
    }

    public Configuration parseConfig(InputStream in) throws DocumentException, PropertyVetoException, ClassNotFoundException {
        Document document = new SAXReader().read(in);
        Element root = document.getRootElement();
        // 解析并创建数据源
        List<Element> propertyList = root.selectNodes("//property");
        Properties properties = new Properties();
        propertyList.forEach(e -> {
            String name = e.attributeValue("name");
            String value = e.attributeValue("value");
            properties.setProperty(name, value);
        });
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(properties.getProperty("driverClass"));
        dataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        dataSource.setUser(properties.getProperty("username"));
        dataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(dataSource);
        // 解析并存储mapper信息
        List<Element> mapperList = root.selectNodes("//mapper");
        for (Element e : mapperList) {
            String resource = e.attributeValue("resource");
            XmlMapperBuilder mapperBuilder = new XmlMapperBuilder(configuration);
            InputStream mapperStream = Resources.getResourceAsStream(resource);
            mapperBuilder.parse(mapperStream);
        }
        return configuration;
    }
}